package server.util.tickevents;

import adventure.room.RoomManager;
import player.Player;
import player.PlayerManager;
import server.util.Broadcaster;

import java.util.ArrayList;

/**
 *
 * @author Michael Hanns
 *
 */
public class Repopulate implements TickerEvent {

    private ArrayList<RepopLocation> repopQueue;
    private Broadcaster broadcaster;
    private RoomManager rooms;
    private PlayerManager players;
    
    public Repopulate(Broadcaster b, RoomManager r, PlayerManager p) {
        this.broadcaster = b;
        this.rooms = r;
        this.players = p;
        this.repopQueue = new ArrayList<RepopLocation>();
    }

    @Override
    public void executeEvent() {
        repopRooms();
        addRoomsToRepopQueue();
    }

    // Repopulates rooms with original contents
    private void repopRooms() {
        System.out.println("Repopping...");
        int x;
        int y;
        int z;
        for (int c = 0; c < repopQueue.size(); c++) {
            x = repopQueue.get(c).x();
            y = repopQueue.get(c).y();
            z = repopQueue.get(c).z();
            
            if (rooms.roomExists(x, y, z)) {
                // If the amount of ticks necessary to reset counter passed, remove from queue.
                if (rooms.tickPassed(x, y, z)) {
                    repopQueue.remove(c);
                    broadcaster.broadcastToRoom(x, y, z, "\nRoom repopulated.\n");
                    c--;
                }
            }
        }
    }

    // Adds rooms players have been in.
    private void addRoomsToRepopQueue() {
        Player player;
        for (int x = 0; x < players.onlinePlayers(); x++) {
            player = players.getOnlinePlayerAtIndex(x);
            RepopLocation xyz = new RepopLocation(player.x(), player.y(), player.z());
            if (uniqueLocation(xyz)) {
                if (rooms.roomRepops(player.x(),
                        player.y(), player.z())) {
                    repopQueue.add(xyz);
                }
            }
        }
    }

    private boolean uniqueLocation(RepopLocation xyz) {
        for (int x = 0; x < repopQueue.size(); x++) {
            if (repopQueue.get(x).x() == xyz.x()
                    && repopQueue.get(x).y() == xyz.y()
                    && repopQueue.get(x).z() == xyz.z()) {
                return false;
            }
        }
        return true;
    }
}

class RepopLocation {

    private int x;
    private int y;
    private int z;

    RepopLocation(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    int x() {
        return x;
    }

    int y() {
        return y;
    }

    int z() {
        return z;
    }
}
